from PIL import Image
import random

def overlay_images(background_path, overlay_path, output_path, start_index):
    # 打开背景图和要覆盖的图像
    background = Image.open(background_path)
    overlay = Image.open(overlay_path)

    # 获取背景图的宽度和高度
    # background = background.convert("RGB")
    bg_width, bg_height = background.size
    print(bg_width, bg_height)
    # 获取要覆盖图像的宽度和高度
    overlay = overlay.resize((60, 60))
    overlay = overlay.convert("RGBA")
    r, g, b, a = overlay.split()
    overlay_width, overlay_height = overlay.size
    print(overlay_width, overlay_height)
    # 随机生成覆盖位置的左上角坐标
    x = random.randint(0, bg_width - overlay_width)
    y = random.randint(0, bg_height - overlay_height)

    # 将要覆盖的图像粘贴到背景图上
    background.paste(overlay, (x, y), a)

    # 保存输出图像
    output_filename = f"{start_index}.jpg"
    output_path = output_path + output_filename
    background.save(output_path)

    print(f"Image saved as {output_filename}")

# 背景图路径
background_image_path = "C:\\Users\T470S\\anaconda3\\envs\\yolov8_venv\\素材\\playground.jpg"

# 要覆盖的图像路径
overlay_image_path = "C:\\Users\\T470S\\anaconda3\\envs\\yolov8_venv\\素材\\t.png"

# 输出路径
output_directory = "C:\\Users\\T470S\\anaconda3\\envs\\yolov8_venv\\素材\\output\\"

# 生成图像并保存
for i in range(30, 40):  # 从10开始递增
    overlay_images(background_image_path, overlay_image_path, output_directory, i)
